﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Xml;
using Universe.WCF.Behaviors;

namespace Universe.TrafficProfiler
{
    class ModelBuilder
    {
        public static ProcessListModel Build()
        {
            var ret = new ProcessListModel();
            Process[] procs = Process.GetProcesses();
            foreach (var proc in procs)
            {
                try
                {
                    int id = proc.Id;
                    NetNamedPipeBinding binding = new NetNamedPipeBinding();
                    binding.ReaderQuotas = XmlDictionaryReaderQuotas.Max;
                    binding.MaxReceivedMessageSize = Int32.MaxValue;

                    var uri = TrafficPublisher.GetUri(id);
                    using (var channel = new ChannelFactory<ITrafficPublisher>(binding, uri))
                    {
                        channel.Open(TimeSpan.FromSeconds(10));
                        var proxy = channel.CreateChannel();
                        TrafficStatistic onServer;
                        TrafficStatistic onClient;
                        proxy.Get(out onServer, out onClient);
                        ProcessListModel.ProcessInfo pi =
                            new ProcessListModel.ProcessInfo()
                                {
                                    Id = id,
                                    FullPath = proc.MainModule.FileName,
                                    OnClient = onClient,
                                    OnServer = onServer
                                };
                        ret.Processes.Add(pi);
                    }
                }
                catch(Exception ex)
                {
                }
            }

            ret.Processes.Sort((x,y) => x.FullPath.CompareTo(y.FullPath));
            return ret;
        }
    }
}
